<?php

namespace App\Http\Controllers\Auth;

use App\Events\UserRegister;
use App\User;
use App\Utils;
use Illuminate\Support\Facades\Event;
use Validator;
use Illuminate\Http\Request;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use Illuminate\Support\Facades\Auth;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Input;
use Redirect;
use App\Parsedown;
use App\Message;
use Mail;

class AuthController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Registration & Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users, as well as the
    | authentication of existing users. By default, this controller uses
    | a simple trait to add these behaviors. Why don't you explore it?
    |
    */

    use AuthenticatesAndRegistersUsers, ThrottlesLogins;


    /**
     * Reload getLogin method
     * @param Request $request
     * @return mixed
     */
    public function getLogin(Request $request)
    {
        Utils::log($request, 'login');
        if (view()->exists('auth.authenticate')) {
            return view('auth.authenticate');
        }
        $utm = $request->input('utm', 'unknown');
        return view('auth.login', compact('utm'));
    }

    /**
     * Reload getRegister method to accept utm
     * @param Request $request
     * @return mixed
     */
    public function getRegister(Request $request)
    {
        $utm = $request->input('utm', 'unknown');
        return view('auth.register', compact('utm'));
    }

    /**
     * Create a new authentication controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest', ['except' => 'getLogout']);
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => 'required|max:255|unique:users',
            'email' => 'required|email|max:255|unique:users',
            'password' => 'required|confirmed|min:6',
            'utm' => 'required'
        ]);
    }


    /**
     * Send a reset link to the given user.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function postEmail(Request $request)
    {
        $this->validate($request, ['email' => 'required|email']);

        $response = Password::sendResetLink($request->only('email'), function (Message $message) {
            $message->subject($this->getEmailSubject());
        });

        switch ($response) {
            case Password::RESET_LINK_SENT:
                return response()->json(array("res" => true));

            //  return redirect()->back()->with('status', trans($response));

            case Password::INVALID_USER:
                return response()->json(array("res" => false));
            //return redirect()->back()->withErrors(['email' => trans($response)]);
        }
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array $data
     * @return User
     */
    protected function create(array $data)
    {
        $user = User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
        ]);
        $user->utm = $data['utm'];
        $user->save();

        Event::fire(new UserRegister($user));

        return $user;
    }
	public function jsonLogin(Request $request)
    {
        $this->validate($request, [
            $this->loginUsername() => 'required', 'password' => 'required',
        ]);

        // If the class is using the ThrottlesLogins trait, we can automatically throttle
        // the login attempts for this application. We'll key this by the username and
        // the IP address of the client making these requests into this application.
        $throttles = $this->isUsingThrottlesLoginsTrait();

        if ($throttles && $this->hasTooManyLoginAttempts($request)) {
            return $this->sendLockoutResponse($request);
        }

        $credentials = $this->getCredentials($request);

        if (Auth::attempt($credentials, $request->has('remember'))) {
			$arr=array();
			$arr['login']=true;
			return response()->json($arr);
        }

        // If the login attempt was unsuccessful we will increment the number of attempts
        // to login and redirect the user back to the login form. Of course, when this
        // user surpasses their maximum number of attempts they will get locked out.
        if ($throttles) {
            $this->incrementLoginAttempts($request);
        }
		$arr=array();
		$arr['login']=false;
		$arr['hint']=$this->getFailedLoginMEssage();
		return response()->json($arr);
    }
}
